<?php

!defined('IN_HC') && exit('Misquoted');

/**
 * Simple db class
 */
class mysqldb
{

    public $conn;
    public $rows = array();
    private $db_host;
    private $db_user;
    private $db_pwd;
    private $db_name;
    private $db_charset;
    const INSERT_COMMON     = 0;//普通插入
    const INSERT_IGNORE     =1;//ignore
    const INSERT_ON_UPDATE  = 2;//on duplicate key update

    public function __construct($db_host, $db_user, $db_pwd, $db_name, $db_charset='utf8', $db_fix='')
    {
        $this->db_host = $db_host;
        $this->db_user = $db_user;
        $this->db_pwd = $db_pwd;
        $this->db_name = $db_name;
        $this->db_charset = $db_charset;
    }
    public function conn()
    {
        if(!$this->conn)
        {
            $this->conn = @mysql_connect($this->db_host, $this->db_user, $this->db_pwd, TRUE) or die('can not link to mysql');
            mysql_select_db($this->db_name, $this->conn) or die('db not found');
            mysql_query("SET NAMES '{$this->db_charset}'", $this->conn);
        }
    }

    public function query($sql, $type = '')
    {
        $this->conn();

        if(!($query = @mysql_query($sql, $this->conn)))
        {
            if(mysql_errno() == 2006)
            {
                mysql_close($this->conn);
                $this->conn = NULL;
                $this->conn();
                // $query = @mysql_query($sql, $this->conn) or die('sql:' . $sql . ' - ' . mysql_errno() . ' - ' . mysql_error());
                $query = @mysql_query($sql, $this->conn) or die();
            }
            elseif ($type == 'SILENT') {
                return $query;
            }
            else
            {
                /* 记录日志*/
                // $day = date('Ymd');
                // $path = '/data/log-data/irun/sqlerr/';
                // !file_exists($path) && mkdir($path);
                // $logName = 'sqlerr.txt';

                // $params = array_merge($_GET, $_POST);

                // $logInfo = '['.date('Y-m-d H:i:s')."]\tmysql_errno:[". mysql_errno() ."]\tmysql_error:[". mysql_error()."]\t";
                // $logInfo .= 'QUERY_STRING:' . urldecode(http_build_query($params, NULL, '&'))."\n";

                // $fp = fopen($path.$logName, "a");
                // fwrite($fp, $logInfo);
                // fclose($fp);
                // die();
                die('sql:' . $sql . ' - ' . mysql_errno() . ' - ' . mysql_error());
            }
        }

        return $query;
    }
    // 返回错误代码
    public function errno()
    {
        return mysql_errno($this->conn);
    }
    // 返回第一行第一列的数据
    public function getOne($sql, $type='num')
    {
        $this->rows = $this->getRow($sql, $type);
        if(!is_array($this->rows))
        {
            return false;
        }
        foreach($this->rows as $v)
        {
            return $v;
        }
    }

    // 返回第一行数据
    public function getRow($sql, $type='assoc')
    {
        unset($this->rows);
        $query = $this->query($sql);
        if(!$query)
        {
            return false;
        }
        if($type == 'num')
        {
            $type = 'row';
        }
        $func = 'mysql_fetch_' . $type;
        $this->rows = $func($query);

        return $this->rows;
    }
    
    public function getCol($sql, $type='num')
    {
        $this->rows = array();
        
        $query = $this->query($sql);
        if(!$query)
        {
            return false;
        }
        if($type == 'num')
        {
            $type = 'row';
        }
        $func = 'mysql_fetch_' . $type;
        while($row = $func($query))
        {
            $this->rows[] = $row[0];
        }
        return $this->rows;
    }
    
    // 返回所有数据
    public function getAll($sql, $type='assoc')
    {
        $this->rows = array();
        
        $query = $this->query($sql);
        if(!$query)
        {
            return false;
        }
        if($type == 'num')
        {
            $type = 'row';
        }
        $func = 'mysql_fetch_' . $type;
        while($row = $func($query))
        {
            $this->rows[] = $row;
        }
        return $this->rows;
    }

    // 数据更新（insert or update）
    public function update($sql)
    {

        if(strtolower(substr($sql, 0, 7)) == 'replace')
        {
            $sql = substr($sql, 0, 7) . ' LOW_PRIORITY' . substr($sql, 7);

        }
        elseif(strpos($sql, 'HIGH_PRIORITY') === FALSE)
        {
            $sql = substr($sql, 0, 6) . ' LOW_PRIORITY' . substr($sql, 6);
        }
        $query = $this->query($sql, $this->conn);
        return $query;
    }
    
    /**
     * 添加一行数据
     * @param string $sql
     * @return int
     */
    public function insert($sql)
    {
        $insertId = 0;
        
        $query = $this->query($sql, $this->conn);
        $query && $insertId = mysql_insert_id($this->conn);
        
        return $insertId;
    }

    /**
     * 添加一行，如果主键已存在则更新当条记录
     * @param string $tableName
     * @param array $cols
     * @return boolean
     */
    public function updateRowTable($tableName, array $cols)
    {
        $setStr = common::arrayToString($cols);

        return $this->update("insert into {$tableName} set {$setStr} on duplicate key update {$setStr}");
    }
    public function insertRowTable($tableName, array $cols){
        $setStr = common::arrayToString($cols);

        return $this->insert("insert into {$tableName} set {$setStr} on duplicate key update {$setStr}");
    }


    /**
     * 获取
     * @param string $tableName
     * @param array $cols
     * @param string $where
     * @param string $order
     * @return array
     */
    public function getRowTable($tableName, array $cols = array(), $where = NULL, $order = NULL)
    {
        $sql = "select " . (!empty($cols) ? implode(',', $cols) : '*') . " from {$tableName}";
        $where && $sql .= " where {$where}";
        $order && $sql .= " order by {$order}";
        $sql .= ' limit 1';

        return $this->getRow($sql);
    }
    /**
     * 删除数据
     * @param string $tableName
     * @param string $where
     * @return boolean
     */
    public function delDataTable($tableName, $where = NULL)
    {
        $sql = "delete from {$tableName}";
        $where && $sql .= " where {$where}";

        return $this->update($sql);
    }

    /**
     * 插入记录（优化）
     * @param string $tableName
     * @param array $params
     * @param int $type  0：普通，1：ignore，2：on duplicate key update
     * @return int
     */
    public function insertRow($tableName, array $params = array(), $type = self::INSERT_COMMON)
    {
        $result = 0;

        $setStr = common::arrayToString($params);

        $ignoreString = $colsString = '';
        $type == 1 && $ignoreString = 'ignore';
        $type == 2 && $colsString .= " on duplicate key update {$setStr}";

        $sql = "insert {$ignoreString} into {$tableName} set {$setStr}{$colsString}";
        $result = $this->insert($sql);

        return $result;
    }

    public function __destruct()
    {
        is_object($this->conn) && $this->conn->mysql_close();
        unset($this->query, $this->rows);
    }

}

?>
